package com.tchintech.pay.view.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;

import com.lljjcoder.citypickerview.widget.CityPicker;
import com.tchintech.pay.R;
import com.tchintech.pay.delegate.BoundcaedActivityDelegate;
import com.tchintech.pay.frame.presenter.ActivityPresenter;
import com.tchintech.pay.model.entity.HttpCode;
import com.tchintech.pay.model.entity.User;
import com.tchintech.pay.net.OkhttpClientTest;
import com.tchintech.pay.utils.AppConst;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/5 0005.
 * 绑定银行卡
 */

public class BoundcaedActivity extends ActivityPresenter<BoundcaedActivityDelegate> implements View.OnClickListener {

    private Intent intent = new Intent();
    private String name, banknum, usernum, bankphone, bankaddress, province, city;
    private Handler handler;
    private Map<String, String> map;
    private final String url_bonndcard = "Bound.bundCard";
    private String bankType = "";
    private String bankname = "";
    private String card_type = "";
    private String bound_enter = "";
    private String pcaddress = "";
    private String bank_number = "";
    private String id = "";
    /**
     * 是否首次绑卡
     */
    private Boolean isfirst;
    private EditText ed_address;

    @Override
    protected void initView() {
        super.initView();
        viewDelegate.setTv_title("银行卡绑定");
        viewDelegate.setVisible();
        viewDelegate.setOnClickListener(this, R.id.iv_back, R.id.bt_submit, R.id.ed_bankname, R.id.ed_bankaddress, R.id.ed_address);
        handler();
        ed_address = viewDelegate.get(R.id.ed_address);
    }


    @Override
    protected void initData() {
        super.initData();

        id = getIntent().getStringExtra("id");
        isfirst = getIntent().getBooleanExtra("isfirst", false);
        bound_enter = getIntent().getStringExtra("bound_enter");
    }

    private void handler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                hideProgressDialog();
                switch (msg.what) {
                    case HttpCode.networkabnormal:
                        showMsg("当前网络不可用");
                        break;
                    case HttpCode.http_failed:
                        showMsg("连接失败");
                        break;
                    case HttpCode.http_timeout:
                        showMsg("请求超时");
                        break;
                    case HttpCode.bonndcard:
                        try {
                            JSONObject json = new JSONObject(msg.obj.toString());
                            if (json.getString("ret").equals("1")) {
                                manageData(json);
                            } else {
                                showMsg(json.getString("msg"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        break;
                    case HttpCode.CARDTYPE:
                        try {
                            JSONObject json = new JSONObject(msg.obj.toString());
                            if (json.getBoolean("validated")) {
                                if (json.getString("cardType").equals("CC")) {
                                    //借贷卡/信用卡
                                    card_type = "00";
                                    if (!isfirst) {
                                        Submit();
                                    } else {
                                        showMsg("首次请绑定储蓄卡");
                                    }
                                } else if (json.getString("cardType").equals("DC")) {
                                    //借记卡/储蓄卡
                                    card_type = "01";
                                    Submit();
                                } else {
                                    // 准贷记卡SCC/QCC
                                    card_type = "02";
                                    if (!isfirst) {
                                        Submit();
                                    } else {
                                        showMsg("首次请绑定储蓄卡");
                                    }
                                }
                            } else {
                                showMsg("请输入正确的银行卡号");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;

                }
            }
        };
    }

    private void manageData(JSONObject json) {
        try {
            if (isfirst) {
                // 返回当前登录人的信息并绑定到全局变量
                User user = getGson().fromJson(json.getString("data"), User.class);
                AppConst.setUser(user);
                //添加手机号到sharepreferes
                getSpUtils().write("phoneNumber", user.getPhone());
                showMsg("绑定成功");
                Activity activity = LoginActivity.aList.get(0);
                //清空静态变量
                LoginActivity.aList = null;
                //跳转主界面
                intent.setClass(BoundcaedActivity.this, MainActivity.class);
                startActivity(intent);
                //关闭loginActivity.class
                activity.finish();
                //关闭当前页面
                finish();
            } else {
                showMsg("绑定成功");
                setResult(RESULT_OK);
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //注册数据组装
    private void Submit() {
        map = new HashMap<String, String>();
        map.put("name", name);
        map.put("banknum", banknum);
        map.put("usernum", usernum);
        map.put("bankname", bankname);
        map.put("banktype", bankType);
        map.put("bankphone", bankphone);
        map.put("card_type", card_type);
        map.put("userid", id);
        map.put("bound_enter", bound_enter);
        map.put("pcaddress", pcaddress);
        map.put("bank_number", bank_number);
        map.put("province", province);
        map.put("city", city);
        showProgressDialog("", "加载中，请稍后...");
        new OkhttpClientTest().path(this, handler, url_bonndcard, map, HttpCode.bonndcard);
    }

    /**
     * 根据银行卡号判断 卡的类型
     *
     * @param card
     */
    private void cardType(String card) {
        String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + card + "&cardBinCheck=true";
        showProgressDialog("", "加载中，请稍后...");
        new OkhttpClientTest().getSync(this, handler, url, HttpCode.CARDTYPE);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ed_bankaddress:
                //选择开户行地址
                if (bankname.equals("")) {
                    showMsg("请选择开户行");
                } else {
                    //开户行选择
                    Intent intent = new Intent();
                    intent.setClass(this, BankProActivity.class);
                    intent.putExtra("bankname", bankname);
                    startActivityForResult(intent, 2);
                }
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.bt_submit:
                judg();
                break;
            case R.id.ed_bankname:
                //银行选择列表
                Intent intent = new Intent();
                intent.setClass(this, BankActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.ed_address:
                //所在地区
                showPcd();
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    bankname = data.getStringExtra("bankName");
                    bankType = data.getStringExtra("bankType");
                    viewDelegate.getEdit().setText(bankname);
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    String address = data.getStringExtra("address");
                    String city = data.getStringExtra("city");
                    String pro = data.getStringExtra("pro");
                    bank_number = data.getStringExtra("bank_number");
                    EditText et = viewDelegate.get(R.id.ed_bankaddress);
                    if (pro.equals(city)) {
                        pcaddress = city + address;
                    } else {
                        pcaddress = pro + city + address;
                    }
                    et.setText(pcaddress);
                }
                break;
            default:


        }


    }

    /**
     * 提交判断
     */
    private void judg() {
        name = viewDelegate.getEdittext(R.id.ed_name);
        banknum = viewDelegate.getEdittext(R.id.ed_banknum);
        usernum = viewDelegate.getEdittext(R.id.ed_usernum);
        bankphone = viewDelegate.getEdittext(R.id.ed_bankphone);
        if (!name.equals("")) {
            if (!banknum.equals("")) {
                if (!usernum.equals("")) {
                    if (!bankname.equals("")) {
                        if (!pcaddress.equals("")) {
                            if (!province.equals("") && province != null) {
                                if (!bankphone.equals("")) {
                                    //开始提交
                                    cardType(banknum);
                                } else {
                                    showMsg("银行预留手机号不能为空");
                                    return;
                                }
                            } else {
                                showMsg("所在地区不能为空");
                            }
                        } else {
                            showMsg("开户行地址不能为空");
                            return;
                        }
                    } else {
                        showMsg("银行名称不能为空");
                        return;
                    }
                } else {
                    showMsg("身份证号不能为空");
                    return;
                }
            } else {
                showMsg("银行卡号不能为空");
                return;
            }
        } else {
            showMsg("姓名不能为空");
            return;

        }

    }


    /**
     * 省市县选择
     */
    private void showPcd() {
        CityPicker cityPicker = new CityPicker.Builder(this)
                .textSize(16)
                .title("地址选择")
                .titleBackgroundColor("#FFFFFF")
                .confirTextColor("#696969")
                .cancelTextColor("#696969")
                .province("陕西省")
                .city("西安市")
                .district("碑林区")
                .textColor(Color.parseColor("#000000"))
                .provinceCyclic(true)
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(7)
                .itemPadding(10)
                .onlyShowProvinceAndCity(false)
                .build();
        cityPicker.show();
        cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
            @Override
            public void onSelected(String... citySelected) {
                //省份
                province = citySelected[0];
                //城市
                city = citySelected[1];
                //区县（如果设定了两级联动，那么该项返回空）
                String district = citySelected[2];
                //邮编
                String code = citySelected[3];

                //为TextView赋值

                ed_address.setText(province.trim() + "-" + city.trim() + "-" + district.trim());


            }
        });
    }

    @Override
    protected Class<BoundcaedActivityDelegate> getDelegateClass() {
        return BoundcaedActivityDelegate.class;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清空静态变量
        LoginActivity.aList = null;
    }
}
